package com.suxin.webflux.service;

import com.suxin.webflux.domain.User;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;

@Service
public class UserHandler {

    private UserServiceImpl userService;

    public UserHandler(UserServiceImpl userService) {
        this.userService = userService;
    }

    public Mono<ServerResponse> getUserById(ServerRequest request) {
        String id = request.pathVariable("id");
        Mono<User> userMono = this.userService.getId(Integer.parseInt(id));
        return userMono.flatMap(user -> {
            return ServerResponse
                    .ok()
                    .contentType(MediaType.APPLICATION_JSON)
                    .bodyValue(fromValue(user)) // 放入body值
                    .switchIfEmpty(ServerResponse.notFound().build()); // 如果为空的话
        });
    }

    public Mono<ServerResponse> getAll(ServerRequest request) {
        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON)
                .body(userService.getList(), User.class);
    }

    public Mono<ServerResponse> save(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class);
        return ServerResponse.ok().build(this.userService.save(userMono));
    }

}
